// Copyright (C) 1953-2020 NUDT
// Verilog module name - flowid_lookup
// Version: V3.2.0.20210722
// Created:
//         by - fenglin 
////////////////////////////////////////////////////////////////////////////
// Description:
//         determine whether a table lookup is required
//         extract flow_id from descriptor,and complete the table
///////////////////////////////////////////////////////////////////////////

`timescale 1ns/1ps

module flowid_lookup
(
       i_clk,
       i_rst_n,
       
       iv_md,
       i_md_wr,
       
       ov_ram_raddr,
       o_ram_rd,

       ov_md,
       o_md_wr
);

// I/O
// clk & rst
input                  i_clk  ;                   //125Mhz
input                  i_rst_n;
// descriptor from p0
(*MARK_DEBUG="true"*)input      [299:0]     iv_md  ;
(*MARK_DEBUG="true"*)input                  i_md_wr;
// read addr to RAM
(*MARK_DEBUG="true"*)output reg [13:0]      ov_ram_raddr;
(*MARK_DEBUG="true"*)output reg             o_ram_rd;
// pkt_bufid and pkt_type and outport to forword
(*MARK_DEBUG="true"*)output reg [299:0]     ov_md;
(*MARK_DEBUG="true"*)output reg             o_md_wr;

//////////////////////////////////////////////////
//      extract flow_id and lookup table        //
//////////////////////////////////////////////////
reg  [299:0] rv_md_1;
reg          r_md_wr_1;
reg  [299:0] rv_md_2;
reg          r_md_wr_2;
always @(posedge i_clk or negedge i_rst_n) begin
    if(i_rst_n == 1'b0)begin       
        ov_ram_raddr            <= 14'h0;
        o_ram_rd                <= 1'h0;
        
        rv_md_1                 <= 300'b0;
        r_md_wr_1               <= 1'b0;     
    end                        
    else begin
        if(i_md_wr == 1'b1)begin
            if(iv_md[111:96] == 16'h8100)begin //dmid,need to flowid table
                ov_ram_raddr  <= iv_md[128:115];//flow_id
                o_ram_rd      <= 1'h1;
                
                rv_md_1       <= iv_md;
                r_md_wr_1     <= i_md_wr; 
            end
            else begin                    //dmid,not need to flowid table
                ov_ram_raddr  <= 14'h0;
                o_ram_rd      <= 1'h0;
                
                rv_md_1       <= iv_md;
                r_md_wr_1     <= i_md_wr; 
            end
        end
        else begin
            ov_ram_raddr            <= 14'h0;
            o_ram_rd                <= 1'h0;
            
            rv_md_1                 <= 300'b0;
            r_md_wr_1               <= 1'b0;
        end
    end
end

always @(posedge i_clk) begin// this signal have to delay 2 cycle,beacuse of the read ram data had wait two cycle
    rv_md_2                 <= rv_md_1;
    r_md_wr_2               <= r_md_wr_1;
    
    ov_md                   <= rv_md_2;
    o_md_wr                 <= r_md_wr_2;          
end

endmodule